package com.cuijian.demo.controller;

import com.cuijian.demo.dto.OrderCreateRequest;
import com.cuijian.demo.mq.MQConstants;
import com.cuijian.demo.service.RocketMQProducerService;
import com.cuijian.demo.util.JsonUtil;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.cuijian.demo.common.JsonResult;
import com.cuijian.demo.model.LogisticsOrder;
import com.cuijian.demo.model.User;
import com.cuijian.demo.util.TokenManager;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Path("/api/order")
public class LogisticsOrderController extends Controller {

    /**
     * 获取当前用户的订单列表
     */
    public void list() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        Long userId = tokenInfo.getUserId();

        int page = getInt("page", 1);
        int size = getInt("size", 10);
        Integer status = getInt("status"); // 可选的状态筛选

        try {
            Page<LogisticsOrder> orderPage;
            if (status != null) {
                // 根据状态筛选
                orderPage = LogisticsOrder.dao.paginate(
                        page, size,
                        "SELECT *",
                        "FROM logistics_order WHERE user_id = ? AND status = ? ORDER BY create_time DESC",
                        userId, status
                );
            } else {
                // 获取所有订单
                orderPage = LogisticsOrder.dao.paginate(
                        page, size,
                        "SELECT *",
                        "FROM logistics_order WHERE user_id = ? ORDER BY create_time DESC",
                        userId
                );
            }

            // 转换数据格式
            Map<String, Object> result = new HashMap<>();
            result.put("list", orderPage.getList());
            result.put("totalRow", orderPage.getTotalRow());
            result.put("pageNumber", orderPage.getPageNumber());
            result.put("pageSize", orderPage.getPageSize());
            result.put("totalPage", orderPage.getTotalPage());

            renderJson(JsonResult.success(result).toMap());

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("查询失败: " + e.getMessage()).toMap());
        }
    }

    /**
     * 获取订单详情方法
     */
    public void detail() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        Long userId = tokenInfo.getUserId();

        Long orderId = getLong("id");
        String trackingNumber = get("trackingNumber");

        if (orderId == null && trackingNumber == null) {
            renderJson(JsonResult.error("订单ID或物流单号不能为空").toMap());
            return;
        }

        try {
            LogisticsOrder order;
            if (orderId != null) {
                order = LogisticsOrder.dao.findById(orderId);
            } else {
                order = LogisticsOrder.dao.findByTrackingNumber(trackingNumber);
            }

            if (order == null) {
                renderJson(JsonResult.error("订单不存在").toMap());
                return;
            }

            // 检查订单是否属于当前用户
            if (!order.getUserId().equals(userId)) {
                renderJson(JsonResult.error("无权访问此订单").toMap());
                return;
            }

            // 返回订单详情
            Map<String, Object> orderInfo = convertOrderToMap(order);
            renderJson(JsonResult.success(orderInfo).toMap());

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("查询失败: " + e.getMessage()).toMap());
        }
    }

    /**
     * 创建物流订单方法
     */
    public void create() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        Long userId = tokenInfo.getUserId();

        String trackingNumber;
        String recipientName;
        String recipientAddress;
        String recipientPhone;
        String logisticsCompany;
        String remarks;

        // 检查是否为JSON请求
        if (JsonUtil.isJsonRequest(this)) {
            OrderCreateRequest createRequest = JsonUtil.getJsonData(this, OrderCreateRequest.class);
            if (createRequest == null) {
                renderJson(JsonResult.error("请求数据不能为空").toMap());
                return;
            }
            trackingNumber = createRequest.getTrackingNumber();
            recipientName = createRequest.getRecipientName();
            recipientAddress = createRequest.getRecipientAddress();
            recipientPhone = createRequest.getRecipientPhone();
            logisticsCompany = createRequest.getLogisticsCompany();
            remarks = createRequest.getRemarks();
        } else {
            // 表单格式
            trackingNumber = get("trackingNumber");
            recipientName = get("recipientName");
            recipientAddress = get("recipientAddress");
            recipientPhone = get("recipientPhone");
            logisticsCompany = get("logisticsCompany");
            remarks = get("remarks");
        }

        // 参数验证
        if (trackingNumber == null || trackingNumber.trim().isEmpty()) {
            renderJson(JsonResult.error("物流单号不能为空").toMap());
            return;
        }

        if (recipientName == null || recipientName.trim().isEmpty()) {
            renderJson(JsonResult.error("收件人姓名不能为空").toMap());
            return;
        }

        if (recipientAddress == null || recipientAddress.trim().isEmpty()) {
            renderJson(JsonResult.error("收件地址不能为空").toMap());
            return;
        }

        if (recipientPhone == null || recipientPhone.trim().isEmpty()) {
            renderJson(JsonResult.error("收件人电话不能为空").toMap());
            return;
        }

        if (logisticsCompany == null || logisticsCompany.trim().isEmpty()) {
            renderJson(JsonResult.error("物流公司不能为空").toMap());
            return;
        }

        try {
            // 检查物流单号是否已存在
            if (LogisticsOrder.dao.isTrackingNumberExists(trackingNumber)) {
                renderJson(JsonResult.error("物流单号已存在").toMap());
                return;
            }

            // 创建新订单
            LogisticsOrder order = new LogisticsOrder();
            order.set("user_id", userId);
            order.set("tracking_number", trackingNumber);
            order.set("recipient_name", recipientName);
            order.set("recipient_address", recipientAddress);
            order.set("recipient_phone", recipientPhone);
            order.set("logistics_company", logisticsCompany);
            order.set("remarks", remarks);
            order.set("status", LogisticsOrder.STATUS_PENDING);
            order.set("order_time", new Date());
            order.set("create_time", new Date());
            order.set("update_time", new Date());

            boolean success = order.save();
            if (success) {
                // 发送订单创建消息
                try {
                    RocketMQProducerService producerService = new RocketMQProducerService();

                    // 方式1：发送完整订单信息
                    producerService.sendOrderCreatedMessage(order);

                    // 方式2：发送简化版订单信息（可选）
                    producerService.sendSimpleOrderCreatedMessage(
                            order.getId(),
                            trackingNumber,
                            recipientName,
                            logisticsCompany
                    );

                    // 方式3：发送异步消息（可选）
                    producerService.sendAsyncMessage(
                            MQConstants.TOPIC_ORDER,
                            MQConstants.TAG_ORDER_CREATED,
                            "ASYNC_ORDER_CREATED_" + trackingNumber,
                            order,
                            () -> {
                                System.out.println("✅ 异步订单创建消息发送成功回调");
                                // 这里可以执行成功后的额外操作
                            },
                            () -> {
                                System.err.println("❌ 异步订单创建消息发送失败回调");
                                // 这里可以执行失败后的处理
                            }
                    );
                } catch (Exception e) {
                    System.err.println("❌ 订单创建消息发送异常: " + e.getMessage());
                    // 消息发送失败不影响主业务流程
                }
                renderJson(JsonResult.success("订单创建成功").toMap());
            } else {
                renderJson(JsonResult.error("订单创建失败").toMap());
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("创建失败: " + e.getMessage()).toMap());
        }
    }


    /**
     * 更新订单信息
     */
    public void update() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        Long userId = tokenInfo.getUserId();

        Long orderId = getLong("id");
        String recipientName = get("recipientName");
        String recipientAddress = get("recipientAddress");
        String recipientPhone = get("recipientPhone");
        String logisticsCompany = get("logisticsCompany");
        String remarks = get("remarks");
        Integer status = getInt("status");

        if (orderId == null) {
            renderJson(JsonResult.error("订单ID不能为空").toMap());
            return;
        }

        try {
            LogisticsOrder order = LogisticsOrder.dao.findById(orderId);
            if (order == null) {
                renderJson(JsonResult.error("订单不存在").toMap());
                return;
            }

            // 检查订单是否属于当前用户
            if (!order.getUserId().equals(userId)) {
                renderJson(JsonResult.error("无权修改此订单").toMap());
                return;
            }

            // 更新字段
            if (recipientName != null) order.set("recipient_name", recipientName);
            if (recipientAddress != null) order.set("recipient_address", recipientAddress);
            if (recipientPhone != null) order.set("recipient_phone", recipientPhone);
            if (logisticsCompany != null) order.set("logistics_company", logisticsCompany);
            if (remarks != null) order.set("remarks", remarks);
            if (status != null) order.set("status", status);

            order.set("update_time", new Date());

            boolean success = order.update();
            if (success) {
                renderJson(JsonResult.success("订单更新成功").toMap());
            } else {
                renderJson(JsonResult.error("订单更新失败").toMap());
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("更新失败: " + e.getMessage()).toMap());
        }
    }

    /**
     * 删除订单
     */
    public void delete() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        Long userId = tokenInfo.getUserId();

        Long orderId = getLong("id");
        if (orderId == null) {
            renderJson(JsonResult.error("订单ID不能为空").toMap());
            return;
        }

        try {
            LogisticsOrder order = LogisticsOrder.dao.findById(orderId);
            if (order == null) {
                renderJson(JsonResult.error("订单不存在").toMap());
                return;
            }

            // 检查订单是否属于当前用户
            if (!order.getUserId().equals(userId)) {
                renderJson(JsonResult.error("无权删除此订单").toMap());
                return;
            }

            boolean success = order.delete();
            if (success) {
                renderJson(JsonResult.success("订单删除成功").toMap());
            } else {
                renderJson(JsonResult.error("订单删除失败").toMap());
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("删除失败: " + e.getMessage()).toMap());
        }
    }

    /**
     * 标记订单为已签收
     */
    public void markDelivered() {
        // 验证token
        if (!verifyToken()) {
            renderJson(JsonResult.error("未授权访问").toMap());
            return;
        }

        TokenManager.TokenInfo tokenInfo = getTokenInfo();
        Long userId = tokenInfo.getUserId();

        Long orderId = getLong("id");
        if (orderId == null) {
            renderJson(JsonResult.error("订单ID不能为空").toMap());
            return;
        }

        try {
            LogisticsOrder order = LogisticsOrder.dao.findById(orderId);
            if (order == null) {
                renderJson(JsonResult.error("订单不存在").toMap());
                return;
            }

            // 检查订单是否属于当前用户
            if (!order.getUserId().equals(userId)) {
                renderJson(JsonResult.error("无权操作此订单").toMap());
                return;
            }

            boolean success = LogisticsOrder.dao.markAsDelivered(orderId);
            if (success) {
                renderJson(JsonResult.success("订单已标记为已签收").toMap());
            } else {
                renderJson(JsonResult.error("操作失败").toMap());
            }
            if (success) {
                // 发送订单签收消息
                try {
                    RocketMQProducerService producerService = new RocketMQProducerService();
                    producerService.sendOrderDeliveredMessage(orderId, order.getTrackingNumber());
                } catch (Exception e) {
                    e.printStackTrace();
                    // 消息发送失败不影响主流程
                }

                renderJson(JsonResult.success("订单已标记为已签收").toMap());
            } else {
                renderJson(JsonResult.error("操作失败").toMap());
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonResult.error("操作失败: " + e.getMessage()).toMap());
        }
    }

    /**
     * 转换订单对象为Map
     */
    private Map<String, Object> convertOrderToMap(LogisticsOrder order) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", order.getId());
        map.put("userId", order.getUserId());
        map.put("trackingNumber", order.getTrackingNumber());
        map.put("recipientName", order.getRecipientName());
        map.put("recipientAddress", order.getRecipientAddress());
        map.put("recipientPhone", order.getRecipientPhone());
        map.put("logisticsCompany", order.getLogisticsCompany());
        map.put("orderTime", order.getOrderTime());
        map.put("estimatedDelivery", order.getEstimatedDelivery());
        map.put("actualDelivery", order.getActualDelivery());
        map.put("status", order.getStatus());
        map.put("statusText", order.getStatusText());
        map.put("remarks", order.getRemarks());
        map.put("createTime", order.getCreateTime());
        map.put("updateTime", order.getUpdateTime());
        return map;
    }

    /**
     * 验证token
     */
    private boolean verifyToken() {
        String authHeader = getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return false;
        }
        String token = authHeader.substring(7);
        return TokenManager.verifyToken(token);
    }

    /**
     * 获取token信息
     */
    private TokenManager.TokenInfo getTokenInfo() {
        String authHeader = getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return null;
        }
        String token = authHeader.substring(7);
        return TokenManager.getTokenInfo(token);
    }
}